package com.fei.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import http.HttpClientUtil;
import util.JsonUtils;
import util.StringUtils;
import util.XMLDoc;

public class GetLongGuoViedo {
    private static void executeVisite(String url) {
        Map<String, String> headers = new HashMap<String,String>();

        headers.put("User-Agent",
                " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        HttpClientUtil.executeGet(url, headers, null);

    }

    public static void main(String[] args) {
        try {
            new GetLongGuoViedo().getCourseDoc();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void testStart() throws Exception{
        List<VideoInfo> videoInfos = this.getCourseList();
        
        StringBuilder sb = new StringBuilder();
        for(VideoInfo info : videoInfos){
            sb.append(info.getName()).append("\t").append(info.getpId()).append("\t").append(info.getvId()).append("\n\r");
        }
        System.out.println(sb);
    }
    public void start() throws Exception {
        /*List<VideoInfo> videoInfos = this.getCourseList();

        List<FileInfo> fileInfos = getFileInfos(videoInfos);
        
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("D:\\test\\data.data")));
        out.writeObject(fileInfos);
        out.flush();
        out.close();*/
        
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("D:\\test\\data.data")));
        Object obj = in.readObject();
        in.close();
        
        List<FileInfo> fileInfos = (List<FileInfo>) obj;
        
        String prex = "http://ws16.videocc.net/pts/";
        for(FileInfo fileInfo : fileInfos){
            List<FileDes> datas = fileInfo.getFiles();
            
            for(FileDes des : datas){
                String url = prex + des.getFile();
                
                HttpClientUtil.downLoadFile(url, "D:\\test\\" + des.index + ".pts", null);
  
            }
            
            break;
        }
    }

    private List<FileInfo> getFileInfos(List<VideoInfo> videoInfos) {
        // http://ws16.videocc.net/pts/a24911d8d7_inc5u317/3/a24911d8d72c7a3e9f08553be18ceaa3_1_1_126.pts
        String url = "http://ws16.videocc.net/pdx/a24911d8d7/%s/%s_1.pdx";

        List<FileInfo> fileInfos = new ArrayList<FileInfo>();
        for (VideoInfo info : videoInfos) {
            String index = info.getvId().substring(
                    info.getvId().lastIndexOf("_") - 1,
                    info.getvId().lastIndexOf("_"));

            String attr = info.getvId().substring(0,
                    info.getvId().lastIndexOf("_"));

            String dataUrl = String.format(url, index, attr);

            String data = HttpClientUtil.executeGet(dataUrl);

            if (StringUtils.isEmpty(data)) {
                System.out.println("无数据：" + info);
            }
            else {
                FileInfo fileInfo = JsonUtils.readJson2Entity(data,
                        FileInfo.class);
                fileInfos.add(fileInfo);

            }

        }
        
        
        return fileInfos;
    }
    
    private void login(Map<String,String> headers){
        String url = "http://account.roncoo.com/oauth2/authorize?clientId=rcf78a59db0c4c416fa60d80527da2a901&responseType=code&redirectUri=http%3A%2F%2Fwww.roncoo.com%2Flogin%3Ftype%3Dlogcb";
        Map<String , String> params = new HashMap<String,String>();
        params.put("userName", "13691557739");
        params.put("passwd", "wangfei1989612");
        
        String result = HttpClientUtil.executePost(url, headers, params);
        
        System.out.println(result);
    }
    
    private void getCourseDoc() throws Exception{
        
        BufferedReader reader = new BufferedReader(new FileReader(new File("F:\\my\\maven-test\\src\\main\\java\\com\\fei\\test\\DocContent")));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line = reader.readLine()) != null){
            sb.append(line);
        }
        
        reader.close();
        
        String data = sb.toString();
        
        String firstPart = data.substring(
                data.indexOf("<ul class=\"doc_list\">"), data.length());
        data = firstPart.substring(
                firstPart.indexOf("<ul class=\"doc_list\">"),
                firstPart.indexOf("</ul>") + 5);
        
        System.out.println(data);
        
        XMLDoc xmlDoc = new XMLDoc();
        xmlDoc.loadFromXMLString(data);
        NodeList nodeList = XMLDoc.selectNodes("li", xmlDoc.getRootElement());
        
        List<String> docNameUrl = new ArrayList<String>();
        for(int i = 0 ; i < nodeList.getLength();i++){
            Node node = nodeList.item(i);
            
            if(!(node instanceof Element)) continue;
            
            Element element = (Element) node;
            
            Node spanNode = XMLDoc.selectSingleNode("a", element);
            
            Element spanElement = (Element) spanNode;
            
            Node span = XMLDoc.selectSingleNode("span", element);
            try{
            HttpClientUtil.downLoadFile(spanElement.getAttribute("href"), "D:\\test\\doc\\" + span.getTextContent(), null);
            }catch(Exception e){
                System.err.println(span.getTextContent() );;
            }
        }
        
        
    }

    private List<VideoInfo> getCourseList() throws Exception {

        String url = "http://www.roncoo.com/course/view/85d6008fe77c4199b0cdd2885eaeee53#boxTwo";

        String data = HttpClientUtil.executeGet(url);

        String firstPart = data.substring(
                data.indexOf("<div class=\"two_det_o\">"), data.length());
        data = firstPart.substring(
                firstPart.indexOf("<div class=\"two_det_o\">"),
                firstPart.indexOf("</div>") + 6);

        XMLDoc xmlDoc = new XMLDoc();
        xmlDoc.loadFromXMLString(data);

        NodeList nodeList = XMLDoc.selectNodes("p", xmlDoc.getRootElement());

        List<VideoInfo> infos = new ArrayList<VideoInfo>();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (!(node instanceof Element)) {
                continue;
            }

            Element element = (Element) node;

            int childIndex = 0;
            NodeList childNodeList = element.getChildNodes();
            VideoInfo info = new VideoInfo();
            infos.add(info);
            for (int j = 0; j < childNodeList.getLength(); j++) {
                Node childNode = childNodeList.item(j);
                if (!(childNode instanceof Element)) {
                    continue;
                }

                Element childElement = (Element) childNode;

                if (childElement.getNodeName().equals("i")) {
                    continue;
                }

                switch (childIndex) {
                    case 0:
                        info.setIndex(
                                Integer.valueOf(childElement.getTextContent()));
                        break;
                    case 1:
                        info.setName(childElement.getTextContent());
                        break;
                    case 3:
                        info.setpId(childElement.getAttribute("pid"));
                        info.setvId(childElement.getAttribute("vid"));
                        break;
                    case 4:
                        info.setTime(childElement.getTextContent());
                        break;
                    default:
                        break;
                }

                childIndex++;

            }

        }

        return infos;

    }
}

class FileInfo implements Serializable{
    private static final long serialVersionUID = -4651326778743099121L;

    String version = "";

    String drm = "";

    String filesize = "";

    String duration = "";

    String filescount = "";

    List<FileDes> files;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getDrm() {
        return drm;
    }

    public void setDrm(String drm) {
        this.drm = drm;
    }

    public String getFilesize() {
        return filesize;
    }

    public void setFilesize(String filesize) {
        this.filesize = filesize;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public String getFilescount() {
        return filescount;
    }

    public void setFilescount(String filescount) {
        this.filescount = filescount;
    }

    public List<FileDes> getFiles() {
        return files;
    }

    public void setFiles(List<FileDes> files) {
        this.files = files;
    }

}

class FileDes implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = -4495148313441008939L;

    String index = "";

    String position = "";

    String time = "";

    String file = "";

    String size = "";

    String offset = "";

    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getOffset() {
        return offset;
    }

    public void setOffset(String offset) {
        this.offset = offset;
    }

}

class VideoInfo {
    String name = "";

    String pId = "";

    String vId = "";

    Integer index = 0;

    String time = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getpId() {
        return pId;
    }

    public void setpId(String pId) {
        this.pId = pId;
    }

    public String getvId() {
        return vId;
    }

    public void setvId(String vId) {
        this.vId = vId;
    }

    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append("index:").append(index).append(",name:").append(name)
                .append(",pid:").append(pId).append(",vid:").append(vId)
                .append(",time:").append(time);

        return sb.toString();
    }
}
